<?php
/**
 * Author panxu
 * Date   2019/8/13 14:33
 */
namespace App\WebSocket;
use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\RedisPool;
use EasySwoole\EasySwoole\ServerManager;

class WebSocketEvent
{


    public function onOpen(\swoole_websocket_server $svr, \swoole_http_request $req)
    {
        //登陆成功
        //1.标记登陆状态 加入redis
        $token = $req->get['token'];
        if(empty($token))
        {
            return $svr->push($req->fd, $this->getMsg('token is empty init err'));
        }
        $redis = RedisPool::defer();
        if(!$redis->exists($token))
        {
            return $svr->push($req->fd, $this->getMsg('token is expire'));
        }
        $userInfo = json_decode($redis->get($token),true);
        $db       = MysqlPool::defer();
        $db->where('id',$userInfo['id'])->update('ch_user',['status'=>'online']);
        $redis->set('fd_'.$req->fd,$userInfo['id']);
        $redis->set('uid_'.$userInfo['id'],$req->fd);
        //2.发送离线消息
        $fd = $req->fd;
        $infos = $db->where('fuid',$userInfo['id'])->where('type',[1,3],'in')->where('status',2)->get('ch_off_message');
        $count = count($infos);
        //延迟一秒推送
        \EasySwoole\Component\Timer::getInstance()->after(1 * 1000, function ()use ($fd,$count) {
            $svr = ServerManager::getInstance()->getSwooleServer();
            $count > 0 && $svr->push($fd, $this->getMsg($count,'msgbox_count'));
        });
        //实时推送
//        return $svr->push($fd, $this->getMsg($count,'msgbox_count'));
    }


    public function onClose(\swoole_server $server, int $fd, int $reactorId)
    {
        /** @var array $info */
        $info = $server->getClientInfo($fd);
        /**
         * 判断此fd 是否是一个有效的 websocket 连接
         * 参见 https://wiki.swoole.com/wiki/page/490.html
         */
        if ($info && $info['websocket_status'] === WEBSOCKET_STATUS_FRAME) {
            /**
             * 判断连接是否是 server 主动关闭
             * 参见 https://wiki.swoole.com/wiki/page/p-event/onClose.html
             */
            if ($reactorId < 0) {
                echo "server close \n";
            }
            //标记状态位offline
            $redis = RedisPool::defer();
            if($redis->exists('fd_'.$fd))
            {
                $uid = $redis->get('fd_'.$fd);
                $redis->del('fd_'.$fd);
                $redis->del('uid_'.$uid);
                $db       = MysqlPool::defer();
                $db->where('id',$uid)->update('ch_user',['status'=>'offline']);
            }

        }
    }


    protected function getMsg($msg,$type='error'){
        return json_encode(['type'=>$type,'msg'=>$msg]);
    }

}